﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;

namespace Movies
{
    public partial class FormDisplayMoviesInShelve : Form
    {
        public FormDisplayMoviesInShelve()
        {
            InitializeComponent();
        }

        List<MovieDetails> movieDetails;
        List<MovieDetails> validMovieDetails = new List<MovieDetails>();

        
        private void movieButton_Click(object sender, EventArgs e)
        {
            try
            {
                Button buttonClicked = (Button)sender;
                MovieDetails detailsObj = (MovieDetails)buttonClicked.Tag;
                if (detailsObj != null)
                {
                    FormDisplayMovieDetails detailsWin = new FormDisplayMovieDetails(detailsObj);
                    detailsWin.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
            }
        }

        private object locateElementAt(int index, List<MovieDetails> items)
        {
            if (index < items.Count)
            {
                int loop=0;
                foreach (object retObj in items)
                {
                    if (loop == index)
                    {
                        return retObj;
                    }
                    loop++;
                }
            }
            return null;
        }

        private int screenColumns = 0;
        private int screenRows = 0;

        private int getVisibleItems()
        {
            Size availableSpace = containerPanel.Size;
            Size buttonSize = getButtonSize();
            Padding buttonPad = getButtonPadding();
            screenColumns = availableSpace.Width / (buttonSize.Width + buttonPad.Top * 2 );
            screenRows = (availableSpace.Height / (buttonSize.Height + buttonPad.Top * 2)) + 1;
            //movieShelveScroll.LargeChange = screenColumns;
            return screenColumns * screenRows;
        }

        private void processMoviesAtFilter()
        {
            movieDetails = HelperDataProvider.getDataStore().getMovieDefinitions();
            if (HelperDataProvider.getDataStore().isFilterDefined())
            {

                foreach (MovieDetails details in movieDetails)
                {
                    if (HelperDataProvider.getDataStore().isValidOnFilter(details))
                    {
                        validMovieDetails.Add(details);
                    }
                }
            }
            else
            {
                validMovieDetails = movieDetails;
            }
        }

        private void recreateDisplay()
        {
            try
            {
                int value = movieShelveScroll.Value;
                getVisibleItems();
                int newMax = ((validMovieDetails.Count / screenColumns) + 1) - screenRows;

                if (newMax < 0)
                {
                    newMax = 0;
                }
                if (newMax < value )
                {
                    movieShelveScroll.Value = newMax;
                }
                int newMaxValue = ((newMax))+1;
                movieShelveScroll.Maximum = (newMaxValue >= 0 ? newMaxValue : 0);
                int buttonHeight = getButtonSize().Height + getButtonPadding().Top * 2;

                //int screenHeight = screenRows * buttonHeight;
                int newScreenHeight = (newMax + screenRows+1) * buttonHeight+100;
                movieShelvePanel.Height = newScreenHeight;//(newScreenHeight > screenHeight ? newScreenHeight : screenHeight);
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
            }
        }

        private void scroll()
        {
            int value = movieShelveScroll.Value;
            movieShelvePanel.Top = -(value * (getButtonSize().Height + getButtonPadding().Top*2))-4;
        }

        private Button[] movieButton = null;
        private int processFirstStack = 0;
        private void initiateMovieLoad()
        {

            if (!(movieDetails != null && movieDetails.Count > 0) && !HelperDataProvider.getDataStore().isMoviesDefined())
            {
                if (!WinDisplayControllor.IsShownDone)
                {
                    Form childForm = new FormDefineMovieLocation();
                    WinDisplayControllor.IsShownDone = true;
                    childForm.ShowDialog();
                }
                else
                {
                    WinDisplayControllor.DisplayDialog("Use Movies menu option to define folder containing Movie(s)");
                }
                statusText.Text = "Movies not found";
                return;
            }
            
            if (validMovieDetails != null && validMovieDetails.Count > 0)
            {
                movieButton = new Button[validMovieDetails.Count];
                int movieIndex = 0;
                progressBar.Maximum = validMovieDetails.Count;
                progressBar.Value = 0;
                progressBar.Show();
                int processFirstStack = getVisibleItems();
                Size butSize = getButtonSize();
                foreach (MovieDetails detailsObj in validMovieDetails)
                {
                    //String[] details = detailsObj.getDataArray();
                    movieButton[movieIndex] = new Button();
                    movieButton[movieIndex].Tag = detailsObj;
                    movieButton[movieIndex].Text = detailsObj.Name;
                    movieButton[movieIndex].Name = "" + movieIndex;
                    movieButton[movieIndex].Size = butSize;
                    movieButton[movieIndex].TabIndex = 0;
                    movieButton[movieIndex].UseVisualStyleBackColor = true;
                    movieButton[movieIndex].BackColor = Color.Black;
                    movieButton[movieIndex].ForeColor = Color.White;
                    movieButton[movieIndex].Margin = getButtonPadding();
                    movieButton[movieIndex].BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                    movieButton[movieIndex].FlatStyle = FlatStyle.Flat;
                    movieButton[movieIndex].Click += new System.EventHandler(this.movieButton_Click);

                    if (processFirstStack > 0)
                    {
                        String imageFile = detailsObj.LocalCoverLocation;
                        if (imageFile != null)
                        {
                            imageFile = imageFile.Replace("file:\\\\", "");
                            if (File.Exists(imageFile) && !imageFile.ToUpper().Trim().Equals("N/A"))
                            {
                                try
                                {
                                    Stream newFile = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                                    Bitmap fileBMP = new Bitmap(newFile);
                                    movieButton[movieIndex].BackgroundImage = fileBMP; //(System.Drawing.Image)(resources.GetStream());
                                    fileBMP = null;
                                    newFile.Close();
                                    movieButton[movieIndex].Text = "";
                                }
                                catch (Exception ex)
                                { HelperContentProvider.OmitWarning(ex); }

                            }
                        }
                        processFirstStack--;
                    }
                    this.movieShelvePanel.Controls.Add(movieButton[movieIndex]);
                    movieIndex++;
                    progressBar.Value += 1; 
                }
                recreateDisplay();
                initImageLoad();
            }
            progressBar.Hide();
            if (HelperDataProvider.getDataStore().isFilterDefined())
            {
                clearFilter.Show();
                applyFilterButton.Text = "Modify Filter";
            }
            applyFilterButton.Show();
            //movieShelvePanel.BackColor = Color.Black;
            statusText.Text = getStatus(validMovieDetails.Count, movieDetails.Count);

            
        }

        private String getStatus(int count, int countTotal)
        {
            String status = "";
            if (countTotal == 0)
            {
                status = "Movies not found to be displayed";
            }
            else if (count == 0 && count < countTotal)
            {
                status = "Showing None in " + countTotal + (countTotal > 1 ? " Items" : " Item");
            }
            else if (countTotal == 1 && count == 1)
            {
                status = "Showing Available " + count + " Item";
            }
            else if (count > 1 && count == countTotal)
            {
                status = "Showing All " + count + " Items";
            }
            else if (count > 0 && count < countTotal)
            {
                status = "Showing " + count + " of " + countTotal + (countTotal > 1 ? " Items" : " Item");
            }
            return status;
        }

        private Size getButtonSize()
        {
            int buttonSize = 0;
            try
            {
                buttonSize = Int16.Parse(HelperSettingProvider.Default().ButtonSize);
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
            }

            switch(buttonSize)
            {
                case 1:
                    return (new Size(99, 132));
                case 2:
                    return (new Size(126, 168));
                case 3:
                    return (new Size(150, 200));
            }
            return (new Size(180, 240));
        }

        private Padding getButtonPadding()
        {
            int buttonSize = 0;
            try
            {
                buttonSize = Int16.Parse(HelperSettingProvider.Default().ButtonSize);
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
            }

            switch (buttonSize)
            {
                case 1:
                    return new Padding(10, 10, 10, 10);
                case 2:
                    return new Padding(12, 12, 12, 12);
                case 3:
                    return new Padding(15, 15, 15, 15);
            }
            return new Padding(20, 20, 20, 20);
        }

        private Bitmap getBackground()
        {
            
                            int buttonSize = 0;
            try
            {
                buttonSize = Int16.Parse(HelperSettingProvider.Default().ButtonSize);
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
            }

            switch (buttonSize)
            {
                case 1:
                    return Properties.Resources.NorBG;
                case 2:
                    return Properties.Resources.MedBG;
                case 3:
                    return Properties.Resources.LargBG;
            }
            return Properties.Resources.LargerBG;
        }

        private void initImageLoad()
        {
            Thread t = new Thread(delegate()
            {
                loadImages();
            });
            t.Start();
        }

        delegate void LoadImages();
        private void loadImages()
        {
            if (progressBar.InvokeRequired)
            {
                LoadImages d = new LoadImages(loadImages);
                this.Invoke(d, new object[] { });
            }
            else{

            for (int index = processFirstStack; index < movieButton.Length; index++)
            {
                Control moviesBut = movieButton[index];
                if (moviesBut.Tag == null)
                {
                    continue;
                }
                MovieDetails details = (MovieDetails)moviesBut.Tag;
                String imageFile = details.LocalCoverLocation;
                //Console.WriteLine(imageFile);
                if (imageFile != null)
                {
                    imageFile = imageFile.Replace("file:\\\\", "");
                    if (File.Exists(imageFile) && !imageFile.ToUpper().Trim().Equals("N/A"))
                    {
                        try
                        {
                            Stream newFile = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                            Bitmap fileBMP = new Bitmap(newFile);
                            moviesBut.BackgroundImage = fileBMP; //(System.Drawing.Image)(resources.GetStream());
                            fileBMP = null;
                            newFile.Close();
                            moviesBut.Text = "";
                            
                        }
                        catch (Exception ex)
                        { HelperContentProvider.OmitWarning(ex); }
                    }
                }
            }
            }
        }

        delegate void InitMovieLoad();
        private void initiateMovieLoadFromThread()
        {
            if (progressBar.InvokeRequired)
            {
                try
                {
                    InitMovieLoad d = new InitMovieLoad(initiateMovieLoadFromThread);
                    this.Invoke(d, new object[] { });
                }
                catch (Exception ex) { HelperContentProvider.OmitWarning(ex); }
            }
            else
            {
                initiateMovieLoad();
            }
        }



        private void button1_Click(object sender, EventArgs e)
        {
            this.Dispose();
            WinDisplayControllor.ShowMovieList();
            
        }

        private void applyFilterButton_Click(object sender, EventArgs e)
        {
            WinDisplayControllor.ShowApplyFilterWin();
        }

        private void clearFilter_Click(object sender, EventArgs e)
        {
            clearFilter.Hide();
            HelperDataProvider.getDataStore().addFilter(null);
            WinDisplayControllor.DisposeApplyFilterWin();
            WinDisplayControllor.ApplyChangesOnLoadedWin();

        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            processMoviesAtFilter();
            initiateMovieLoadFromThread();
        }


        private void MovieRak_Load(object sender, EventArgs e)
        {
            movieShelvePanel.Height = containerPanel.Height;
            movieShelvePanel.Width = containerPanel.Width;
            containerPanel.BackgroundImage = getBackground();
            backgroundWorker.RunWorkerAsync();
        }

        private void movieShelveScroll_ValueChanged(object sender, EventArgs e)
        {
            scroll();
        }

        private void MovieShelve_Resize(object sender, EventArgs e)
        {
            recreateDisplay();
        }

        private void menuStrip2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        
        private void moveDownToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            int max = movieShelveScroll.Maximum;
            int value = movieShelveScroll.Value;

            if (value < max)
            {
                movieShelveScroll.Value = value + 1;
            }
        }

        private void moveUpToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            int min = movieShelveScroll.Minimum;
            int value = movieShelveScroll.Value;

            if (min < value)
            {
                movieShelveScroll.Value = value - 1;
            }
        }

        private void moveEndToolStripMenuItem_Click(object sender, EventArgs e)
        {
            movieShelveScroll.Value = movieShelveScroll.Maximum;
        }

        private void moveHomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            movieShelveScroll.Value = movieShelveScroll.Minimum;
        }

        

    }
}
